package com.recharge.web.controller;


import com.recharge.common.domain.PageDO;
import com.recharge.common.result.ResultDO;
import com.recharge.common.result.web.ObjectResponse;
import com.recharge.common.util.FunctionUtil;
import com.recharge.domain.query.CardVoucherQueryDO;
import com.recharge.domain.vo.CardVoucherDO;
import com.recharge.domain.vo.GoodsDO;
import com.recharge.domain.vo.UserLoginDO;
import com.recharge.service.CardVoucherService;
import io.swagger.annotations.ApiOperation;
import net.sf.jxls.transformer.XLSTransformer;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 卡密表 前端控制器
 * </p>
 *
 * @author Reagan
 * @since 2020-10-20
 */
@RestController
@RequestMapping("/card-voucher")
public class CardVoucherController extends BaseController{

    @Autowired
    private CardVoucherService cardVoucherService;

    @Value("${file.card-voucher.template}")
    private String fileTemplatePath;

    /**
     * 充值卡添加
     * @param cardVoucherDO(
     *     "provider_id"充值卡提供商的id,
     *    "voucher_no":卡的凭证号,
     *    "voucher_password":密码,
     *    "create_mothod":1接口导入，2本地导入)
     * @return ObjectResponse
     * */
    //@RequiresPermissions("card-voucher:addCardVoucher")
    @RequestMapping(value = "/addCardVoucher.html",method = RequestMethod.POST)
    @ApiOperation(value = "充值卡添加",notes = "")
    public @ResponseBody
    ObjectResponse addCardVoucher(@RequestBody CardVoucherDO cardVoucherDO){

        ObjectResponse response = new ObjectResponse();
        //从token获取添加卡密的用户信息
        UserLoginDO userLoginDO = getUserLoginInfo();
        //将用户的用户名存入卡密信息中
        cardVoucherDO.setCreator(userLoginDO.getUsername());
        ResultDO result = cardVoucherService.add(cardVoucherDO);
        if(!result.isSuccess()) {
            response.setStatus(result.getErrorCode().getCode());
            response.setMsg(result.getErrorCode().getMsg());
        }
        return  response;
    }

    /**
     * 编辑充值卡
     * @param cardVoucherDO
     * @return ObjectResponse
     */
   // @RequiresPermissions("card-voucher:editCardVoucher")
    @RequestMapping(value = "/editCardVoucher.html",method = RequestMethod.POST)
    @ApiOperation(value = "编辑充值卡",notes = "")
    public @ResponseBody
    ObjectResponse  editCardVoucher(@RequestBody CardVoucherDO cardVoucherDO){

        ObjectResponse response = new ObjectResponse();
        //从token获取添加卡密的用户信息
        UserLoginDO userLoginDO = getUserLoginInfo();
        //将用户的用户名存入卡密信息中
        cardVoucherDO.setCreator(userLoginDO.getUsername());
        ResultDO result = cardVoucherService.edit(cardVoucherDO);
        if(!result.isSuccess()) {
            response.setStatus(result.getErrorCode().getCode());
            response.setMsg(result.getErrorCode().getMsg());
        }
        return  response;

    }
    /**
     * 返回充值卡详情
     * @param cardVoucherDO 里面会有充值卡id
     * @return ObjectResponse
     */
   // @RequiresPermissions("card-voucher:get")
    @RequestMapping(value = "/get.html",method = RequestMethod.POST)
    @ApiOperation(value = "查询充值卡",notes = "")
    public @ResponseBody
    ObjectResponse get(@RequestBody CardVoucherDO cardVoucherDO ){

        ObjectResponse<CardVoucherDO> response = new ObjectResponse<>();
        ResultDO result = cardVoucherService.get(cardVoucherDO.getId());
        if(!result.isSuccess()) {
            response.setStatus(result.getErrorCode().getCode());
            response.setMsg(result.getErrorCode().getMsg());
        } else {
            try {
                //如果isSuccess返回ture，说明查询成功。将result里面的数据转存入response返回
                response.setData((CardVoucherDO) result.getModel(ResultDO.FIRST_MODEL_KEY));
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return  response;
    }
    /**
     * 删除充值卡
     * @param cardVoucherDO 有充值卡id
     *
     * @return ObjectResponse
     */
   // @RequiresPermissions("card-voucher:delete")
    @RequestMapping(value = "/delete.html",method = RequestMethod.POST)
    @ApiOperation(value = "删除充值卡",notes = "")
    public @ResponseBody
    ObjectResponse delete(@RequestBody CardVoucherDO cardVoucherDO){
        ObjectResponse response = new ObjectResponse();
        //从token获取删除操作的用户
        UserLoginDO userLoginDO = getUserLoginInfo();
        //传入充值卡的id和操作的用户
        ResultDO result = cardVoucherService.remove(cardVoucherDO.getId(), userLoginDO.getUsername());
        if(result.isSuccess()) {
            //操作失败
            response.setData(null);
        } else {
            //操作执行成功
            response.setStatus(result.getErrorCode().getCode());
            response.setMsg(result.getErrorCode().getMsg());
        }
        return  response;
    }
    /**
     * 查找充值卡
     * @param query 多条件查询的封装对象
     * @return ObjectResponse
     */
    @RequiresPermissions("card-voucher:page")
    @RequestMapping(value = "/page.html",method = RequestMethod.POST)
    @ApiOperation(value = "查找充值卡",notes = "")
    public @ResponseBody
    ObjectResponse<PageDO> find(@RequestBody CardVoucherQueryDO query){
        ObjectResponse<PageDO> response = new ObjectResponse();
        ResultDO result = cardVoucherService.find(query);
        if(!result.isSuccess()){
            //返回异常
            response.setStatus(result.getErrorCode().getCode());
            response.setMsg(result.getErrorCode().getMsg());
        }else {
            //正常返回结果
            response.setData((PageDO)result.getModel(ResultDO.FIRST_MODEL_KEY));
        }
        return  response;
    }
    /**
     * 批量删除充值卡
     * @param params
     * @return  ObjectResponse
     */
    @RequestMapping(value = "/deleteList.html",method = RequestMethod.POST)
    @ApiOperation(value = "批量删除充值卡",notes = "")
    public @ResponseBody
    ObjectResponse deleteList(@RequestBody CardVoucherDO params){
        ObjectResponse<Object> response = new ObjectResponse<>();
        //获取需要删除的id数组
        String[] ids = params.getCardVoucherIds().split(",");
        ResultDO result = cardVoucherService.removeList(ids, getUserName());
        if(result.isSuccess()) {
            //正常返回
            response.setData(null);
        } else {
            //异常返回
            response.setStatus(result.getErrorCode().getCode());
            response.setMsg(result.getErrorCode().getMsg());
        }
        return  response;
    }
    /**
     * 批量添加充值卡
     * @param params
     * @return ObjectResponse
     */
    @RequestMapping(value = "/addBatch.html",method = RequestMethod.POST)
    @ApiOperation(value = "批量添加充值卡",notes = "")
    public @ResponseBody
    ObjectResponse addBatch(@RequestBody CardVoucherDO params){
        ObjectResponse<Object> response = new ObjectResponse<>();
        //获取批量添加的充值卡
        List<CardVoucherDO> cardVoucherDOList = params.getParams();
        ResultDO result = cardVoucherService.insertAll(cardVoucherDOList);
        if(result.isSuccess()) {
            response.setData(null);
        } else {
            response.setStatus(result.getErrorCode().getCode());
            response.setMsg(result.getErrorCode().getMsg());
        }
        return  response;
    }
    /**
     * 根据产品返回卡密
     * @param params
     * @return  ResultDO
     */
    @RequestMapping(value = "/getByGoodsNo.html",method = RequestMethod.POST)
    @ApiOperation(value = "根据产品Id返回卡密",notes = "")
    public @ResponseBody
    ObjectResponse<List<CardVoucherDO>>  getByGoodsNo(@RequestBody CardVoucherQueryDO params){
        ObjectResponse<List<CardVoucherDO>> response = new ObjectResponse<>();
        //获取充值卡的商品编号
        Integer goodsNo = params.getGoodsNo();
        ResultDO result = cardVoucherService.queryCardByGoodsNo(params);
        if(result.isSuccess()) {
            //正常返回结果
            response.setData((List<CardVoucherDO>)result.getModel(ResultDO.FIRST_MODEL_KEY));
        } else {
            response.setStatus(result.getErrorCode().getCode());
            response.setMsg(result.getErrorCode().getMsg());
        }
        return  response;
    }
    /**
     * 根据充值卡id修改充值卡的状态
     * @param  param
     * @return  ObjectResponse
     */
    @RequestMapping(value = "/editStatus.html",method = RequestMethod.POST)
    @ApiOperation(value = "根据产品Id修改卡密状态",notes = "")
    public @ResponseBody
    ObjectResponse editStatus(@RequestBody CardVoucherDO param){
        ObjectResponse<Object> response = new ObjectResponse<>();
        ResultDO result = cardVoucherService.editStatus(param.getId(), param.getStatus());
        if(result.isSuccess()) {
            //修改成功
            response.setData(null);
        } else {
            response.setStatus(result.getErrorCode().getCode());
            response.setMsg(result.getErrorCode().getMsg());
        }
        return  response;
    }

    @RequiresPermissions("card-voucher:excelUpload")
    @RequestMapping(value = "/excelUpload.html" ,method = RequestMethod.POST)
    @ApiOperation(value = "excel文件导入",notes = "")
    public @ResponseBody  ObjectResponse<Object> excelUpload(MultipartFile file, Integer goodsNo,Long denomination) {
        ObjectResponse<Object> response = new ObjectResponse<>();
        GoodsDO goodsDO = new GoodsDO();
        goodsDO.setGoodsNo(goodsNo);
        goodsDO.setDenomination(denomination);
        ResultDO result = cardVoucherService.getExcel(file,goodsDO);
        if(result.isSuccess()) {
            //导入成功
            response.setData(null);
        } else {
            response.setStatus(result.getErrorCode().getCode());
            response.setMsg(result.getErrorCode().getMsg());
        }
        return response;
    }

    @RequiresPermissions("card-voucher:excel-download")
    @RequestMapping(value = "/excelDownload.html" ,method = RequestMethod.POST)
    @ApiOperation(value = "excel文件导出",notes = "")
    public void excelDownload(@RequestBody CardVoucherQueryDO query, HttpServletResponse response) {
        ResultDO result = cardVoucherService.findList(query);
        List<CardVoucherDO> list= (List<CardVoucherDO>) result.getModel(ResultDO.FIRST_MODEL_KEY);
        List<Object> downloadList = new ArrayList<>();
        list.stream().forEach( item -> {
            Map<String,Object> data = new HashMap<>();
            data.put("a1", item.getProviderName() );
            data.put("a2", item.getDenomination() );
            data.put("a3", item.getGoodsNo());
            data.put("a4", item.getGoodsName() );
            data.put("a5", item.getVoucherNo() );
            data.put("a6", item.getStatus() == 1 ? "有效" : item.getStatus() == 0 ? "已核销" : "无效卡" );
            downloadList.add(data);
        });

        Map map = new HashMap();
        map.put("data",downloadList);
        map.put("fun", new FunctionUtil());
        try{
            InputStream is = new FileInputStream(fileTemplatePath);
            // 实例化 XLSTransformer 对象
            XLSTransformer xlsTransformer = new XLSTransformer();
            // 获取 Workbook ，传入 模板 和 数据
            Workbook workbook =  xlsTransformer.transformXLS(is,map);

            // 设置文件名
            response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode("卡密列表.xls" ,"UTF-8"));
            // 写出文件
            OutputStream os = new BufferedOutputStream( response.getOutputStream() );
            // 输出
            workbook.write(os);
            // 关闭和刷新管道，不然可能会出现表格数据不齐，打不开之类的问题
            is.close();
            os.flush();
            os.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

}

